﻿using DTcms.Core.Common.Helper;
using System.Text.RegularExpressions;

namespace DTcms.Core.Web.Helpers
{
    /// <summary>
    /// 通用处理帮助类
    /// </summary>
    public class UtilsHelper
    {
        /// <summary>
        /// 替换内容图片地址为API绝对路径
        /// </summary>
        public static string ReplaceImagesPath(string? content)
        {
            if (string.IsNullOrEmpty(content))
            {
                return string.Empty;
            }
            var baseApi = Appsettings.GetValue(new string[] { "ApiConfig", "BaseUrl" }); //获取API地址
            Regex reg = new Regex("IMG[^>]*?src\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^\']*)')", RegexOptions.IgnoreCase);
            MatchCollection m = reg.Matches(content);
            foreach (Match math in m)
            {
                string imgUri = math.Groups[1].Value;
                if(imgUri.StartsWith("http://")|| imgUri.StartsWith("https://"))
                {
                    continue;
                }
                string newImgPath = baseApi + imgUri;
                content = content.Replace(imgUri, newImgPath);
            }
            return content;
        }
    }
}
